package com.demo.word.controller;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.io.FileInputStream;
import java.util.Iterator;
import java.util.List;

/**
 * @Author likz
 * @Date 2024/12/20 9:16
 * @Description  https://blog.csdn.net/lakerswz/article/details/127539916
 **/
public class WordTable {


    public static void main(String[] args) {
        try {


        XWPFDocument xwpf = new XWPFDocument(new FileInputStream("C:\\Users\\likz\\Desktop\\健帆\\CTCAE500.docx"));//得到word文档的信息
        Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
        // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
        int set = 0, total = 4;
        int num = set;
        // 过滤前面不需要的表格
//        for (int i = 0; i < set - 1; i++) {
//            it.hasNext();
//            it.next();
//        }
        while (it.hasNext()) {
            XWPFTable table = it.next();
            System.out.println("这是第" + num + "个表的数据开始----");
            List<XWPFTableRow> rows = table.getRows();
            //读取每一行数据
            for (int i = 0; i < rows.size(); i++) {
                XWPFTableRow row = rows.get(i);
                //读取每一列数据
                List<XWPFTableCell> cells = row.getTableCells();
                for (int j = 0; j < cells.size(); j++) {
                    XWPFTableCell cell = cells.get(j);
                    //输出当前的单元格的数据
                   // System.out.print(cell.getText() + "\t");
                    System.out.println("第"+i+"行,第"+j+"列数据:"+cell.getText()+"\t");
                }
                System.out.println("第"+i+"行结束");
            }
            // 过滤多余的表格
//            while (num < total) {
//                it.hasNext();
//                it.next();
//                num += 1;
//            }
            System.out.println("这是第" + num + "个表的数据结束----");
            num += 1;

        }
        }catch (Exception e){

        }


    }

}
